package com.hyb.hybmodulesfront.listener;



import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.SignupConstants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.RemoteSignupService;
import com.ruoyi.system.api.domain.Signup;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Lazy(value = false)
@RabbitListener(
        queues = {"activityQueue"}
)
public class RabbitmqListener {

    @Autowired
    RemoteSignupService remoteSignupService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @RabbitHandler
    public void signup(Signup signup, Channel channel, Message message) throws Exception {
        //利用redis防止重复消费
        //计算过期时间
        try {
            String s = redisTemplate.opsForValue().get(SignupConstants.SIGN_UP_CONSUMER_KEY + signup.getActivityId() + ":" + signup.getUserId());
            if(StringUtils.isEmpty(s)){
                remoteSignupService.add(signup, SecurityConstants.INNER);
                redisTemplate.opsForValue().set(SignupConstants.SIGN_UP_CONSUMER_KEY+signup.getActivityId()+":"+signup.getUserId(),"1",10,TimeUnit.MINUTES);
                //手动确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }catch (Exception e){
            //拒绝确认
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            throw new GlobalException("com.hyb.hybmodulesfront.listener.RabbitmqListener#signup消费异常");

        }
    }

}
